<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-30
 * Time: 11:12:54
 * Info:
 */

namespace plugin\book\app\controller\admin;

use support\Request;
use plugin\book\app\model\Book as BookModel;
use plugin\book\app\model\Doc as DocModel;

class BookController
{

    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $count = BookModel::count();
            $data  = BookModel::order('sort asc,id asc')->select()->toArray();
            foreach ($data as $key => $v) {
                $data[$key]['count'] = (new DocModel)->bookCount($v['id']);
            }

            return json(['code' => 0, 'count' => $count, 'data' => $data, 'msg' => 'ok']);
        }

        return view('admin/book/index');
    }

    public function add(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['title'])) {
                return json(['code' => 0, 'msg' => '标题不能为空']);
            }
            $param['admin_id'] = cmf_get_admin_id();

            BookModel::create($param);

            return json(['code' => 200, 'msg' => '操作成功']);
        }

        return view('admin/book/add');
    }

    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['id'])) {
                return json(['code' => 0, 'msg' => '参数错误']);
            }
            if (empty($param['title'])) {
                return json(['code' => 0, 'msg' => '标题不能为空']);
            }
            BookModel::update($param, ['id' => $param['id']]);

            return json(['code' => 200, 'msg' => '操作成功']);
        }
        $id = $request->get('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        $data = BookModel::find($id);
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '获取数据失败']);
        }

        return view('admin/book/edit', ['data' => $data]);
    }

    public function delete(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        BookModel::where('id', $id)->delete();

        return json(['code' => 200, 'msg' => '删除成功']);
    }

}
